package com.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

public class JDBCDemo {

    public static void showStudents(){
        //通过工具类获取连接
        try(Connection conn = DataSourceUtils.getConnection()){
            PreparedStatement ps = conn.prepareStatement("select * from student");
            ResultSet rs = ps.executeQuery();
            while(rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                int age = rs.getInt("age");
                System.out.println(id+" "+name+" "+age);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    // 搜索学生，输入学生名字的一部分，搜索出所有名字包含这个字符串的学生
    public static void searchStudents(String stuName){
        //通过工具类获取连接
        try(Connection conn = DataSourceUtils.getConnection()){
            PreparedStatement ps = conn.prepareStatement("select * from student where name like ?");
            ps.setString(1, "%"+stuName+"%");
            ResultSet rs = ps.executeQuery();
            while(rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                int age = rs.getInt("age");
                System.out.println(id+" "+name+" "+age);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //showStudents();
//        searchStudents("小");
//        JDBCUtils.update("insert into student(name,age,gender,cellphone,address) values(?,?,?,?,?)",
//                "王大六",32,"男","15345678901","北京");
        List<Student> list =JDBCUtils.query(Student.class,"select * from student");
        for(Student stu : list){
            System.out.println(stu);
        }
    }
}
